package com.antipov.odp.server;

import com.antipov.odp.IOHelper;
import com.antipov.odp.pojo.I;

import java.io.*;
import java.net.Socket;

/**
 * Created with IntelliJ IDEA.
 * User: Andrew Antipov
 * Date: 18.02.14
 * Time: 23:15
 */
public class Handler extends Thread {
	private Socket socket;
	private BufferedReader in;
	private PrintWriter out;
	private StreamTokenizer tok;

	public Handler(Socket socket) {
		this.socket = socket;
		init();
	}

	private void init() {
		try {
			this.in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			this.out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())));
			this.tok = new StreamTokenizer(in);
		} catch (IOException e) {
			throw new RuntimeException();
		}
	}

	@Override
	public void run() {
		System.out.println("Run");
		try {
			while(true) {
				String action = IOHelper.nextString(tok);
				if(action.equals("End")) {
					break;
				}
				I first = IOHelper.readNext(tok);
				I second = IOHelper.readNext(tok);
				I res = sum(first, second);
				out.println(res.toString());
				out.flush();
			}
			System.out.println("End");
		} catch (Throwable t) {
			t.printStackTrace();
		} finally {
			try {
				socket.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	private static I sum(I a, I b) {
		int[] resArray = new int[a.getArray().length + b.getArray().length];
		for(int i = 0; i < a.getArray().length; i++) {
			resArray[i] = a.getArray()[i];
		}
		for(int i = 0; i < b.getArray().length; i++) {
			resArray[i+a.getArray().length] = b.getArray()[i];
		}
		a.setArray(resArray);
		a.setX(a.getX() + b.getX());
		return a;
	}
}
